package com.example.springboot.service;

import com.example.springboot.Mapper.ContentMapper;
import com.example.springboot.Mapper.DocCustMapper;
import com.example.springboot.Mapper.DocMapper;
import com.example.springboot.exception.BusinessException;
import com.example.springboot.exception.BusinessExceptionCode;
import com.example.springboot.pojo.Content;
import com.example.springboot.pojo.Doc;
import com.example.springboot.pojo.DocExample;
import com.example.springboot.request.DocQueryRequest;
import com.example.springboot.request.DocSaveRequest;
import com.example.springboot.response.DocQueryResponse;
import com.example.springboot.response.PageResponse;
import com.example.springboot.util.CopyUtil;
import com.example.springboot.util.RedisUtil;
import com.example.springboot.util.RequestContext;
import com.example.springboot.util.SnowFlake;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;

@Service
public class ServiceDoc {

    private static final Logger LOG= LoggerFactory.getLogger(ServiceDoc.class);

    @Resource
    private DocMapper docMapper;
    
    @Resource
    private DocCustMapper docCustMapper;

    @Resource
    private ContentMapper contentMapper;

    @Resource
    private SnowFlake snowFlake;

    @Resource
    public RedisUtil redisUtil;

    //这里把原来的list方法去掉了分页功能，一次查出所有数据也就不需要分页了，改名为all方法。
    public List<DocQueryResponse> all(Long ebookId){

        DocExample docExample = new DocExample();
        docExample.createCriteria().andEbookIdEqualTo(ebookId);
        //这里调用了Example类的设置顺序的方法，“sort asc”是代表按照sort的值顺序asc（排列）
        docExample.setOrderByClause("sort asc");
        List<Doc> docList=docMapper.selectByExample(docExample);

        //列表复制
        List<DocQueryResponse> list= CopyUtil.copyList(docList, DocQueryResponse.class);
        return list;
    }

    /*
    * 保存
    * */
    public void save(DocSaveRequest request){
        Doc doc=CopyUtil.copy(request,Doc.class);
        Content content=CopyUtil.copy(request, Content.class);
        if(ObjectUtils.isEmpty(request.getId())){
            //新增
            doc.setId(snowFlake.nextId());
            doc.setViewCount(0);
            doc.setVoteCount(0);
            docMapper.insertSelective(doc);

            content.setId(doc.getId());
            contentMapper.insertSelective(content);
        }
        else{
            //更新
            docMapper.updateByPrimaryKey(doc);
            int count=contentMapper.updateByPrimaryKeyWithBLOBs(content);
            if(count ==0){
                contentMapper.insert(content);
            }
        }
    }

    /*
    * 删除
    * */
    public void delete(Long id){
        docMapper.deleteByPrimaryKey(id);
    }
    /*
     * 删除整个树枝
     * */
    public void delete(List<String> ids){
        DocExample docExample = new DocExample();
        DocExample.Criteria criteria = docExample.createCriteria();
        criteria.andIdIn(ids);
        docMapper.deleteByExample(docExample);

    }

    public String findContent(Long id){
        Content content=contentMapper.selectByPrimaryKey(id);
        //文档阅读数加一
        docCustMapper.increaseViewCount(id);
        if(ObjectUtils.isEmpty(content))
        {
            return "";
        }else{
            return content.getContent();
        }
    }

/*
* 点赞
* */
    public void vote(Long id){
        docCustMapper.increaseVoteCount(id);

        // docMapperCust.increaseVoteCount(id);
        // 远程IP+doc.id作为key，24小时内不能重复
        String ip = RequestContext.getRemoteAddr();
        if (redisUtil.validateRepeat("DOC_VOTE_" + id + "_" + ip, 5000)) {
            docCustMapper.increaseVoteCount(id);
        } else {
            throw new BusinessException(BusinessExceptionCode.VOTE_REPEAT);
        }
    }

    public PageResponse<DocQueryResponse> list(DocQueryRequest docQueryRequest){



        DocExample docExample = new DocExample();
        //这里调用了Example类的设置顺序的方法，“sort asc”是代表按照sort的值顺序asc（排列）
        docExample.setOrderByClause("sort asc");
        DocExample.Criteria criteria = docExample.createCriteria();



        PageHelper.startPage(docQueryRequest.getPage(), docQueryRequest.getSize());
        List<Doc> docList=docMapper.selectByExample(docExample);


        PageInfo<Doc> pageInfo = new PageInfo<>(docList);
        LOG.info("总行数："+pageInfo.getTotal());
        LOG.info("总页数：" + +pageInfo.getPages());



        /*List<DocResponse> responseList=new ArrayList<>();
        for( Doc doc:docList){
            *//*DocResponse docResponse=new DocResponse();
            BeanUtils.copyProperties(doc,docResponse);*//*

            //使用CopyUtil代替上面的那两句
        DocResponse docResponse = CopyUtil.copy(doc,DocResponse.class);


            responseList.add(docResponse);

        }*/


        //列表复制
        List<DocQueryResponse> list= CopyUtil.copyList(docList, DocQueryResponse.class);

        PageResponse<DocQueryResponse> pageResponse = new PageResponse<>();
        pageResponse.setTotal(pageInfo.getTotal());
        pageResponse.setList(list);
        return pageResponse;
    }

    public void updateEbookInfo(){
        docCustMapper.updateEbookInfo();
    }
}
